package com.hsgene.generator.controller;

import com.hsgene.common.util.exception.CommonErrorCode;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.generator.service.GeneratorService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * ID生成器Controller
 *
 * @author wangbing
 * @version 1.0, 2018/6/28
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/generator")
public class GeneratorController {

    @Autowired
    private GeneratorService generatorService;

    /**
     * 生成id
     *
     * @param type   id类型
     * @param prefix id前缀
     * @return 生成结果
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ApiResult<GeneratorDto> generator(
            @RequestParam(name = "type", required = false) String type,
            @RequestParam(name = "prefix", required = false) String prefix) {
        return generatorService.generate(type, prefix);
    }

    /**
     * 64位编号生成器
     *
     * @param prefixType   前缀
     * @param workerId     工作ID
     * @param datacenterId 数据中心ID
     * @return
     */
    @GetMapping("number")
    public ApiResult<GeneratorDto> numberGenerator(String prefixType, Integer workerId, Integer datacenterId) {
        if (workerId == null) {
            workerId = 0;
        }
        if (datacenterId == null) {
            datacenterId = 0;
        }
        if (StringUtils.isEmpty(prefixType)) {
            return ApiResult.fail(CommonErrorCode.REQUIRED_NUMBER_TYPE);
        }
        return generatorService.numberGenerator(prefixType, workerId, datacenterId);
    }
}
